package edu.gmu.projects.fireresponder.gui;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import edu.gmu.projects.fireresponder.FirstResponder;
import edu.gmu.projects.fireresponder.R;
import edu.gmu.projects.fireresponder.comm.UDPBroadcast;
import edu.gmu.projects.fireresponder.environment.Building;
import edu.gmu.projects.fireresponder.environment.Safespot;
import edu.gmu.projects.fireresponder.missionplanner.SituationEnvironment;
import edu.gmu.projects.fireresponder.relevancyengine.RelevanceEngineService;
import edu.gmu.projects.fireresponder.xml.alerts.AlertGenerator;

public class AssetDialogMessageTab extends Activity {

	// UI controls
	private TextView mTitleText;
	private EditText mBodyText;
	private Button confirmButton;
	private ImageView jpgView;
	private Button cameraButton;

	// Variables to be used in program
	private String assetClassValue = "";
	private String assetIdValue = "";
	private double latValue = 0.0;
	private double longValue = 0.0;
	private static final int REQUEST_CODE = 0;

	// Index of scene status selected
	private int itemSelectedIndex = 0;

	// String value of scene status selected
	private String itemSelected = "";

	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.i("AssetDialogMessageTab", "Created activity");

		getApplicationContext().bindService(
				new Intent(AssetDialogMessageTab.this,
						RelevanceEngineService.class), relevanceConnection,
				BIND_AUTO_CREATE);

		setContentView(R.layout.notifications_view);
		setTitle(R.string.view_notifications);

		// Get data from bundle passed in intent
		Bundle bundle = getIntent().getExtras();
		assetClassValue = bundle.getString(SituationMap.ASSET_CLASS);
		assetIdValue = bundle.getString(SituationMap.ASSET_ID);
		latValue = bundle.getDouble(SituationMap.LAT);
		longValue = bundle.getDouble(SituationMap.LNG);

		mTitleText = (TextView) findViewById(R.id.title);
		mTitleText.setFocusable(false); // make control uneditable
		mTitleText.setText(assetIdValue);
		mBodyText = (EditText) findViewById(R.id.body);
		

		cameraButton = (Button) findViewById(R.id.snap);
		// handle camera button click
		cameraButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Perform action on clicks
				Intent cameraIntent = new Intent(getApplicationContext(),
						CameraView.class);
				startActivityForResult(cameraIntent, REQUEST_CODE);
			}
		});

		confirmButton = (Button) findViewById(R.id.confirm);
		// handle button click
		confirmButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// Use the sendResponderAlert method to send information out
				sendResponderAlert(itemSelectedIndex, itemSelected, latValue,
						longValue, mBodyText.getText().toString(),
						FileUtilities.alteredImageData, "image/jpeg");

				FileUtilities.alteredImageData = null;

				// Finalize the click event
				setResult(RESULT_OK);
				finish();
			}
		});

		// Spinner control for status drop down list
		Spinner spinner = (Spinner) findViewById(R.id.spinner);

		ArrayList<String> items = new ArrayList<String>();
		items.add("Fire Seen");
		items.add("People Present");

		if (assetClassValue.compareTo(Building.class.getName()) == 0) {
			items.add("Building Cleared");
			items.add("Unable to Reach");
		} else if (assetClassValue.compareTo(Safespot.class.getName()) == 0) {
			items.add("Safespot Cleared");
		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, items);

		int layoutId = android.R.layout.simple_spinner_dropdown_item;
		adapter.setDropDownViewResource(layoutId);

		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
	}

	@Override
	public void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		Log.i("AsseDialogMessageTab", "New intent requested for this activity");

		setpreview();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.i("AsseDialogMessageTab",
				"Returned to this activity from CameraView Activity");

		setpreview();

	}

	public void setpreview() {

		if (FileUtilities.alteredImageData != null
				&& FileUtilities.alteredImageData.length > 0) {

			jpgView = (ImageView) findViewById(R.id.jpgview);

			//BitmapFactory.Options options = new BitmapFactory.Options();
			//options.inSampleSize = 2;
/*
			Bitmap bitMap = BitmapFactory.decodeByteArray(
					FileUtilities.alteredImageData, 0,
					FileUtilities.alteredImageData.length, options);
*/
			Bitmap bitMap = BitmapFactory.decodeByteArray(
					FileUtilities.alteredImageData, 0,
					FileUtilities.alteredImageData.length);

			// Matrix for rotation of picture
			Matrix m = new Matrix();
			m.postRotate(90);

			Bitmap rotatedBitmap = Bitmap.createBitmap(bitMap, 0, 0, bitMap
					.getWidth(), bitMap.getHeight(), m, false);

			// make a drawable from Bitmap to allow to set the BitMap
			// to the ImageView
			BitmapDrawable bmd = new BitmapDrawable(rotatedBitmap);

			jpgView.setImageDrawable(bmd);
			jpgView.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getApplicationContext().unbindService(relevanceConnection);

		if (progressDialog != null) {
			progressDialog.dismiss();
		}

		Log.i("AssetDialogMessageTab",
				"Destroyed AssetDialogMessageTab activity");
	}

	// Method to send alerts
	public void sendResponderAlert(int type, String title, double lat,
			double lng, String message, byte[] imageArrayData,
			String imageMimeType) {
		String alert = null;
		Calendar cal = Calendar.getInstance();
		FirstResponder self = SituationEnvironment
				.getSituationEnvironment(this).getSelf();

		if (message == null) {
			Log.i("AssetDialogMessageTab", "Message is null");
		} else {
			Log.i("AssetDialogMessageTab", "Message is " + message);
		}

		if (imageArrayData == null) {
			Log.i("AssetDialogMessageTab", "ImageArraData is null");
		} else {
			Log.i("AssetDialogMessageTab", "ImageArraData length is "
					+ imageArrayData.length);

		}

		switch (type) {
		case 0:
			if (assetClassValue.compareTo(SituationMap.NO_VALUE) != 0) {
				relevanceService.getRelevanceEngine().onResponderSetFireSeen(
						assetIdValue);
			}

			alert = new AlertGenerator().generateResponderFireAlert(self
					.getId(), cal, lat, lng, message, imageArrayData,
					imageMimeType);

			break;
		case 1:
			if (assetClassValue.compareTo(SituationMap.NO_VALUE) != 0) {
				relevanceService.getRelevanceEngine().onResponderSetPeopleSeen(
						assetIdValue);
			}

			alert = new AlertGenerator().generateResponderPeopleObservedAlert(
					self.getId(), cal, lat, lng, message, imageArrayData,
					imageMimeType);

			break;
		case 2:
			if (assetClassValue.compareTo(SituationMap.NO_VALUE) != 0) {
				relevanceService.getRelevanceEngine().onResponderSetCompleted(
						assetIdValue);
			}

			alert = new AlertGenerator().generateResponderBuildingClearedAlert(
					self.getId(), title, cal, lat, lng, message,
					imageArrayData, imageMimeType);

			break;
		case 3:
			if (assetClassValue.compareTo(SituationMap.NO_VALUE) != 0) {
				relevanceService.getRelevanceEngine()
						.onResponderSetUnableToReach(assetIdValue);
			}

			alert = new AlertGenerator().generateResponderBuildingDroppedAlert(
					self.getId(), title, cal, lat, lng, message,
					imageArrayData, imageMimeType);

			break;
		}

		if (alert == null) {
			Log.i("AssetDialogMessageTab", "Alert is null");
		} else {
			Log.i("AssetDialogMessageTab", "Alert is " + alert);
		}

		progressDialog = ProgressDialog.show(this, "Sending Message",
				"Sending...");

		Log.i("AssetDialogMessageTab", "Sending alert");
		new Thread(new AlertSender(alert)).start();
	}

	private class AlertSender implements Runnable {
		String alert;

		public AlertSender(String alert) {
			this.alert = alert;
		}

		public void run() {
			if (alert != null) {
				UDPBroadcast.getUDPBroadcast().send(alert);
				Log.i("AssetDialogMessageTab", "Alert sent");
				handler.sendEmptyMessage(0);
			}
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
		}
	};

	// Status list selection handler
	public class MyOnItemSelectedListener implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {

			itemSelectedIndex = pos;
			itemSelected = parent.getItemAtPosition(pos).toString();
		}

		@SuppressWarnings("unchecked")
		public void onNothingSelected(AdapterView parent) {
			// Do nothing.
		}
	}

	private RelevanceEngineService relevanceService;

	private ServiceConnection relevanceConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName name, IBinder service) {
			relevanceService = ((RelevanceEngineService.LocalBinder) service)
					.getService();

			Log.i("AssetDialogMessageTab",
					"Connected to RelevanceEngineService");
		}

		public void onServiceDisconnected(ComponentName name) {
			relevanceService = null;

			Log.i("AssetDialogMessageTab",
					"Disconnected from RelevanceEngineService");
		}
	};
}